let express = require('express')
let router = express.Router()
let uuid = require("uuid")
let md5 = require("md5")
let Query = require("../tools/db")
let {getToken,verifyToken,api_url,suo} = require("../config/index")


// 注册
router.post("/register", async (req, res, next) => {
    // 1.获取前端的内容
    let { username = "", password = "", repwd = "" } = req.body
    // 2.判断
    if (username == "" || password == "" || repwd == "") {
        next("输入框不能为空")
        return
    }
    if (password != repwd) {
        next("两次输入的密码不一致")
        return
    }
    // 3.查询用户表 是否含有用户名
    let sql1 = `SELECT * FROM e_member WHERE username="${username}"`
    let [,result1]=await Query(sql1)
    if (result1.length>0) {
        next("用户已存在")
        return
    }else{
        // 4.添加到用户表
        let mid = uuid.v4()
        let createdate=Date.now()
        // 密码加密
        password=md5(password+suo)
        let sql2 = `INSERT INTO e_member (mid,username,password,createdate) VALUES ('${mid}','${username}','${password}','${createdate}')`
        let [,result2]=await Query(sql2)
        if (result2.affectedRows>0) {
            res.send({
                status:200,
                msg:"注册成功"
            })
        }else{
            next("注册失败")
        }
    }

})
// 统一验证token
router.use((req,res,next)=>{
    // if (!verifyToken(req.headers.authorization)) {
    //     next("token无效，请登录")
    //     return
    // }
    next()
})
// 登录
router.post("/login",async (req,res,next)=>{
    let {username,password}=req.body
    if (username == "" || password == "" ) {
        next("输入框不能为空")
        return
    }
    // 1.查询用户表中是否含有用户
    password=md5(password+suo)
    let sql = `SELECT * FROM e_member WHERE username='${username}' AND password='${password}'`
    let [,result1]=await Query(sql)
    if (result1.length>0) {
        // 2.登录成功 生成一个token
        let data={
            username,
            password
        }
        let result=getToken(data)
        res.send({
            status:200,
            msg:"ok",
            result:{
                token:result,
                mid:result1[0].mid
            }
        })
    }else{
        next("登录失败")
        return
    }

})


module.exports=router
